package com.musicsonar.android.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.musicsonar.android.activity.MusicSonarActivity;
import com.musicsonar.android.utils.MusicSonarConstant;

public class PhoneReceiver extends BroadcastReceiver {

	public void onReceive(Context context, Intent intent) {
		/*Bundle bundle = intent.getExtras();
		Object pdus[] = (Object[]) bundle.get("pdus");
		if(pdus != null){
			for (int n = 0; n < pdus.length; n++) {
				SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[n]);
				String msg = message.getDisplayMessageBody();
				msg = msg.toLowerCase();
				// Receiving text message
			}
		}*/
		PhoneListener phoneListener = new PhoneListener();
		TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
	}

	private class PhoneListener extends PhoneStateListener{

		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
				case TelephonyManager.CALL_STATE_RINGING:
					//Toast.makeText(MusicSonarActivity.me, "RING RING... !!!!", Toast.LENGTH_LONG).show();
					if(MusicSonarActivity.mp != null){
						MusicSonarConstant.wasPlaying = MusicSonarActivity.mp.isPlaying();
						if(MusicSonarConstant.wasPlaying){
							MusicSonarActivity.mp.pause();
							MusicSonarConstant.currentPositionPaused = MusicSonarActivity.mp.getCurrentPosition();
						}
					}
					break;
				case TelephonyManager.CALL_STATE_IDLE:
					//Toast.makeText(MusicSonarActivity.me, "LLAMADA FIN", Toast.LENGTH_LONG).show();
					if(MusicSonarActivity.mp != null){
						if(MusicSonarConstant.wasPlaying){
							MusicSonarActivity.mp.seekTo(MusicSonarConstant.currentPositionPaused);
							MusicSonarActivity.mp.start();
						}
					}
					break;
				case TelephonyManager.CALL_STATE_OFFHOOK:
					//Toast.makeText(MusicSonarActivity.me, "Fuck!", Toast.LENGTH_LONG).show();
					if(MusicSonarConstant.currentPositionPaused != 0){
						MusicSonarActivity.mp.seekTo(MusicSonarConstant.currentPositionPaused);
						MusicSonarActivity.mp.start();
					}
					/*
					AudioManager audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
					audioManager.setRouting(AudioManager.MODE_IN_CALL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
					audioManager.setMode(AudioManager.MODE_IN_CALL);

					audioManager.setSpeakerphoneOn(false);
					audioManager.setMicrophoneMute(false);
					audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);*/
					break;
				}
		}

	}
}